package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param loginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO loginDTO) {

        //1、获取openid
        String openId = getOpenId(loginDTO.getCode());
        if (openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //2、调用mapper根据openid查询用户对象
        User user =userMapper.findByOpenId(openId);
        //3、判断用户是否为null
        if (user == null){
            //4、如果为null，插入数据
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
        }


        //5、返回用户对象
        return user;
    }

    @Autowired
    private WeChatProperties weChatProperties;

    private String getOpenId(String code){
        //1、创建Map封装4个参数数据
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("grant_type","authorization_code");
        map.put("js_code",code);
        //2、使用工具类发送请求，并返回json数据
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);
        //3、将数据转换成JSONObject
        JSONObject jsonObject = JSON.parseObject(json);

        //4、解析openId返回
        return jsonObject.getString("openid");
    }
}
